using MallSystembackend.Api.Repository;
using MallSystembackend.Api.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.Linq;
using System.IO;
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;

namespace MallSystembackend.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class HeadPortraitController : ControllerBase
    {
        public IRepository<HeadPortrait> _headPortraitRepository;
        private readonly IConfiguration _configuration;

        public HeadPortraitController(IConfiguration configuration,IRepository<HeadPortrait> headPortraitRepository)
        {
            _configuration = configuration;
            _headPortraitRepository = headPortraitRepository;
        }

        [HttpPost, Route("uploadfiles/{id}")]
        public ActionResult UploadFiles(IFormCollection model,int id)//IFormCollection接口表示与 HttpRequest 一起发送的已分析窗体值
        {
            //如果已经有头像那么上一张头像禁用
            var picture = _headPortraitRepository.Table.Where(x =>x.UsersId==id && x.IsActived==true).FirstOrDefault();
            if(picture !=null){
                picture.IsActived = false;
                _headPortraitRepository.Update(picture);
            }
            // 获得当前应用所在的完整路径（绝对地址）
            var filePath = Directory.GetCurrentDirectory();
            Console.WriteLine(filePath);
            // 通过配置文件获得存放文件的相对路径
            string path = _configuration["UploadFilesPath"];

            // 最终存放文件的完整路径
            var preFullPath = Path.Combine(filePath, path);
            // 如果路径不存在，则创建
            if (!Directory.Exists(preFullPath))
            {
                //Directory公开用于通过目录和子目录进行创建、移动和枚举的静态方法。 此类不能被继承
                Directory.CreateDirectory(preFullPath);
            }

            var resultPath = new List<string>();
            var uploadfiles = new List<HeadPortrait>();
            //遍历请求中的文件集合
            //IFormFile表示http请求发送的文件
            foreach (IFormFile file in model.Files)
            {
                if (file.Length > 0)
                {
                    var fileName = file.FileName;
                    //从此实例检索子字符串。 子字符串在指定的字符位置开始并一直到该字符串的末尾，并返回
                    var extName = fileName.Substring(fileName.LastIndexOf("."));//extName包含了“.”
                    //随机名称
                    var rndName = Guid.NewGuid().ToString("N") + extName;
                    Console.WriteLine(rndName);
                    Console.WriteLine(path);
                    //组合存放图片路径和文件随机名称
                    var tempPath = Path.Combine(path, rndName).Replace("\\", "/");
                    Console.WriteLine(tempPath);
                    //path对包含文件或目录路径信息的 String 实例执行操作             //FileMode指定操作系统打开文件的方式
                    using (var stream = new FileStream(Path.Combine(filePath, tempPath), FileMode.CreateNew))//Path.Combine(_env.WebRootPath, fileName)
                    {
                        Console.WriteLine(stream);
                        //将file文件复制到stream中
                        file.CopyTo(stream);
                    }

                    var tmpFile = new HeadPortrait
                    {
                        UsersId = id,
                        OriginName = fileName,
                        CurrentName = rndName,
                        RelativePath = tempPath,
                        ContentType = file.ContentType
                    };

                    uploadfiles.Add(tmpFile);

                    // 此处地址可能带有两个反斜杠，虽然也能用，比较奇怪，统一转换成斜杠，这样在任何平台都有一样的表现
                    resultPath.Add(tempPath.Replace("\\", "/"));
                }
            }

            _headPortraitRepository.InsertBulk(uploadfiles);

            

            return Ok(new
            {
                Code = 1000,
                Data = uploadfiles.Select(x => new { x.Id }),
                Msg = "上传成功"
            });
        }

        // 根据用户id
        [Route("{id}")]
        [HttpGet]
        public FileContentResult Get(int id)
        {
            //当前文件绝对路径
            var currentPath = Directory.GetCurrentDirectory();

            var fileInfos = _headPortraitRepository.Table;
            var fileInfo = fileInfos.Where(x => x.UsersId == id && x.IsActived==true).ToList();
            // 如果数据库没有找到对应的文件记录，则返回空内容
            if (fileInfo.Count ==0)
            {
                return new FileContentResult(new byte[0], "image/jpeg");
            }

            var fullPath = Path.Combine(currentPath, fileInfo[0].RelativePath);

            var returnPath = Path.Combine("http://localhost:5000/",fileInfo[0].RelativePath);
            
            // 如果在当前文件系统中没有找到文件，则返回空内容
            if (!System.IO.File.Exists(fullPath))
            {
                return new FileContentResult(new byte[0], "image/jpeg");
            }

            //在using范围内文件流自动开启关闭
            using (var sw = new FileStream(fullPath, FileMode.Open))
            {
                var contenttype = fileInfo[0].ContentType;
                var bytes = new byte[sw.Length];
                //从流中读取字节块并将该数据写入给定缓冲区中。
                sw.Read(bytes, 0, bytes.Length);

                return new FileContentResult(bytes, contenttype);
            }
        }
    }

}
